package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.item.dto.CategoryDTO;
import com.leyou.item.entity.Category;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.CategoryMapper;
import com.leyou.item.service.CategoryBrandService;
import com.leyou.item.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public List<CategoryDTO> queryByBrand(Long brandId) {
        // 1.查询中间表，得到分类信息，SELECT * FROM tb_category_brand WHERE brand_id = 18374
        List<CategoryBrand> cbList = categoryBrandService.query().eq("brand_id", brandId).list();
        if(CollectionUtils.isEmpty(cbList)){
            // 资源不存在
            throw new LyException(404, "品牌没有关联的分类！");
        }
        // 2.处理数据，得到分类id的集合
        /*List<Long> idList = new ArrayList<>();
        for (CategoryBrand cb : cbList) {
            idList.add(cb.getCategoryId());
        }*/
        List<Long> ids = cbList.stream().map(CategoryBrand::getCategoryId).collect(Collectors.toList());

        // 3.根据id批量查询分类表，得到分类集合
        List<Category> categories = listByIds(ids);

        // 4.转换DTO并返回
        return CategoryDTO.convertEntityList(categories);
    }
}